<template>
  <div>
    <a-row :gutter="20" style="padding:0 0 20px 0">
      <a-col>
        <a-button type="primary" @click="addRoleModal = true"
          >添加角色</a-button
        >
      </a-col>
    </a-row>
    <a-table
      align="center"
      rowKey="id"
      :columns="columns"
      :data-source="roleList"
      :pagination="false"
      bordered
      childrenColumnName
    >
      <!-- 展开效果 -->
      <template slot="expandedRowRender" slot-scope="record">
        <a-row
          :class="['bdBottom', i1 === 0 ? 'bdTop' : '', 'vCenter']"
          v-for="(item1, i1) in record.children"
          :key="item1.id"
          align="middle"
        >
          <!-- 渲染一级权限 -->
          <a-col :span="5">
            <a-tag
              class="a-tag"
              color="cyan"
              closable
              @close.prevent="removeRightById(record, item1.id)"
              >{{ item1.authName }}</a-tag
            >
            <a-icon type="caret-right" />
          </a-col>
          <!-- 渲染二级和三级权限 -->
          <a-col :span="19">
            <!-- 通过for循环嵌套渲染二级权限 -->
            <a-row
              v-for="(item2, i2) in item1.children"
              :key="item2.id"
              :class="[i2 === 0 ? '' : 'bdTop', 'vCenter']"
            >
              <a-col :span="6">
                <a-tag
                  class="a-tag"
                  color="green"
                  closable
                  @close.prevent="removeRightById(record, item2.id)"
                >
                  {{ item2.authName }}</a-tag
                >
                <a-icon type="caret-right" />
              </a-col>
              <!-- 循环渲染三级权限 -->
              <a-col :span="18">
                <a-tag
                  v-for="item3 in item2.children"
                  :key="item3.id"
                  class="a-tag"
                  color="orange"
                  closable
                  @close.prevent="removeRightById(record, item3.id)"
                >
                  <!--  @close="removeRightById(record, item3.id)" -->
                  {{ item3.authName }}</a-tag
                >
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </template>

      <!-- 操作列 -->
      <a-row slot="operation" slot-scope="dataIndex, record">
        <!-- 编辑按钮 -->
        <a-button
          type="primary"
          icon="edit"
          style="margin:3px"
          @click="showEditModal(record.id)"
          >编辑
        </a-button>
        <!-- 删除按钮 -->
        <a-button
          type="danger"
          icon="delete"
          style="margin:3px"
          @click="removeRoleById(record.id)"
          >删除
        </a-button>
        <!-- 分配角色 -->
        <a-button
          icon="setting"
          style="margin:3px;background:#ffa400;color:#fff"
          @click="showSetRightModal(record)"
        >
          分配权限
        </a-button>
      </a-row>
    </a-table>
    <!-- 添加角色对话框区域 -->
    <a-modal
      title="添加角色"
      :visible="addRoleModal"
      ok-text="确认"
      cancel-text="取消"
      labelAlign="left"
      @ok="addRole"
      @cancel="addRoleModalClosed"
    >
      <a-form-model
        :model="roleForm"
        :rules="addRoleRules"
        ref="roleFormRef"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        board
      >
        <a-form-model-item label="角色名" prop="roleName">
          <a-input v-model="roleForm.roleName"></a-input>
        </a-form-model-item>
        <a-form-model-item label="描述（可空）" prop="roleDesc">
          <a-input v-model="roleForm.roleDesc"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 编辑角色对话框区域 -->
    <a-modal
      title="修改角色"
      :visible="editModalVisible"
      ok-text="确认"
      cancel-text="取消"
      labelAlign="left"
      @ok="editRoleInfo"
      @cancel="editModalClosed"
    >
      <a-form-model
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <a-form-model-item label="角色id">
          <a-input v-model="editForm.roleId" disabled></a-input>
        </a-form-model-item>
        <a-form-model-item label="角色名" prop="roleName">
          <a-input v-model="editForm.roleName"></a-input>
        </a-form-model-item>
        <a-form-model-item label="描述" prop="">
          <a-input v-model="editForm.roleDesc"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 分配权限对话框区域  -->
    <a-modal
      title="分配权限"
      :visible="setRightModalVisible"
      width="50%"
      @ok="allotRights"
      @cancel="setRightModalClosed"
      cancelText="取消"
      okText="确定"
    >
      <a-tree
        :tree-data="rightsList"
        :replace-fields="replaceFields"
        checkable
        key="id"
        default-expand-all
        v-model="defKeys"
        @check="onSelectChange"
      ></a-tree>
    </a-modal>
  </div>
</template>

<script>
export default {
  created() {
    this.getRolesList()
  },
  data() {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      roleList: [],
      addRoleModal: false,
      roleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 5, message: '请输入合法的角色名', trigger: 'blur' }
        ]
      },
      editForm: {},
      editModalVisible: false,
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 5, message: '请输入合法的角色名', trigger: 'blur' }
        ]
      },
      setRightModalVisible: false,
      rightsList: [],
      // 默认选中的节点Id值数组
      defKeys: [],
      roleId: '',
      // 所有中和半选中的key
      selectedAllKeys: [],
      replaceFields: { children: 'children', title: 'authName', key: 'id' },
      // 表格列数据
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '角色名称',
          dataIndex: 'roleName'
        },
        {
          title: '角色描述',
          dataIndex: 'roleDesc'
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'operation' }
        }
      ]
    }
  },
  methods: {
    // 获取角色数据
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.roleList = res.data
      // console.log(this.roleList)
    },
    // 添加角色处理函数
    addRole() {
      this.$refs.roleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.roleForm)
        // console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        this.addRoleModal = false
        this.getRolesList()
      })
    },
    // 关闭添加角色对话框
    addRoleModalClosed() {
      this.$refs.roleFormRef.resetFields()
      this.addRoleModal = false
    },
    // 展示修改角色对话框
    async showEditModal(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色信息失败！')
      }
      this.editForm = res.data
      this.editModalVisible = true
    },
    // 关闭修改角色对话框
    editModalClosed() {
      this.$refs.editFormRef.resetFields()
      this.editModalVisible = false
    },
    // 提交修改角色确认按钮处理函数
    editRoleInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新角色信息失败')
        }
        this.editModalVisible = false
        this.getRolesList()
        this.$message.success('更新角色信息成功！')
      })
    },
    // 删除角色按钮处理函数
    removeRoleById(id) {
      const that = this
      this.$confirm({
        content: '此操作将永久删除' + id + '用户, 是否继续?',
        cancelText: '取消',
        okText: '确定',
        async onOk() {
          const { data: res } = await that.$http
            .delete(`roles/${id}`)
            .catch(err => err)
          if (res.meta.status !== 200) {
            return that.$message.error('删除角色失败！')
          }
          that.$message.success('删除角色成功！')
          that.getRolesList()
        },
        onCancel() {
          that.$message.info('已经取消删除')
        }
      })
    },
    // 删除权限
    removeRightById(role, rightId) {
      const that = this
      this.$confirm({
        content: '此操作将永久删除该角色的此项权限, 是否继续?',
        cancelText: '取消',
        okText: '确定',
        async onOk() {
          const { data: res } = await that.$http
            .delete(`roles/${role.id}/rights/${rightId}`)
            .catch(err => err)
          if (res.meta.status !== 200) {
            return that.$message.error('删除权限失败！')
          }
          that.$message.success('删除权限成功！')
          // 重新赋值该行数据
          role.children = res.data
        },
        onCancel() {
          that.$message.info('已经取消删除')
        }
      })
    },
    // 展示分配权限对话框
    async showSetRightModal(role) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限信息失败！')
      }
      this.rightsList = res.data
      this.getLeafKeys(role, this.defKeys)
      this.setRightModalVisible = true
      this.roleId = role.id
      console.log('this.defKeys' + this.defKeys)
    },
    // 获取默认展示的权限 通过递归的形式获取角色下所有三级权限的id,并保存到defKeys数组中
    getLeafKeys(node, arr) {
      // 如果当前 node 节点不包含 children属性,则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 分配权限对话框关闭 清空默认选中数组
    setRightModalClosed() {
      this.defKeys = []
      this.setRightModalVisible = false
    },
    // 节点选中后获取所有父子节点的key包括半选中
    onSelectChange(selectedKeys, info) {
      this.selectedAllKeys = info.halfCheckedKeys.concat(selectedKeys)
    },
    // 点击分配权限确认
    async allotRights() {
      const keys = this.selectedAllKeys
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightModalVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.a-tag {
  margin: 7px;
  padding: 5px;
  font-size: 12px;
}
.bdTop {
  border-top: 1px solid #eee;
}
.bdBottom {
  border-bottom: 1px solid #eee;
}
.vCenter {
  display: flex;
  align-items: center;
}
</style>
